import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'

export default create(subscribeWithSelector((set) => {
  return {
    y: 0,

    distance: 0,
    distanceMax: 15 * 1000,

    lanes: 2,

    // 加速的数量
    energy: 1,

    // 加时的数量
    timer: 1,

    // 可以玩的时间
    duration: 30 * 1000,

    target: 200 * 1000,

    passed: 0,

    moving: undefined,

    player: undefined,

    speed: 10,

    speedMin: 2,

    speedMax: 50,

    speedStep: 30,

    speedDecline: 0,

    state: 0,

    car: {
      x: 0,
      y: 0
    },

    carX: 0,
    carY: 0,


    blocksCount: 10,
    blocksSeed: 0,

    /**
     * Time
     */
    startTime: 0,
    endTime: 0,

    /**
     * Phases
     */
    phase: 'ready',

    // 场景 normal water fire ice
    scene: 'normal',

    change: (key, val) => {
      set(state => {
        return {
          [key]: val
        }
      })
    },

    start: () => {
      set((state) => {
        if (state.phase === 'ready')
        // 开始游戏重置参数
          return {phase: 'playing', startTime: Date.now(),speed:10,distance:0}

        return {}
      })
    },

    restart: () => {
      set((state) => {
        if (state.phase === 'playing' || state.phase === 'ended')
          return {phase: 'ready', blocksSeed: Math.random()}

        return {}
      })
    },

    loss: () => {
      set((state) => {
        if (state.phase === 'playing')
          return {phase: 'loss', endTime: Date.now()}

        return {}
      })
    },

    end: () => {
      set((state) => {
        if (state.phase === 'playing')
          return {phase: 'ended', endTime: Date.now(), speed:10,state: 'narmal'}

        return {}
      })
    }
  }
}))